import 'dart:math';

import 'package:eh_mobile/common/utils/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';

import '../../../../common/values/svg_image.dart';

class LightTempWidget extends StatefulWidget {
  const LightTempWidget(
      {super.key,
      required this.value,
      required this.valueChanged,
      this.maxValue = 6500,
      this.minValue = 2700});

  final double value; //当前色温值
  final double maxValue; // 色温最大值
  final double minValue; // 色温最大值
  final ValueChanged valueChanged;

  @override
  State<LightTempWidget> createState() {
    return LightTempWidgetState();
  }
}

class LightTempWidgetState extends State<LightTempWidget> {
  final _superHeight = 280.r;
  Offset _position = Offset.zero;
  late double _progressValue;
  late Offset _center;
  late Offset _currentOffset;
  late double _radius;

  late double _tempValue = widget.value;
  // 色温差值
  late double _tempDiffValue;

  late Color _currentColor;

  @override
  void initState() {
    _tempDiffValue = widget.maxValue - widget.minValue;
    _progressValue = (widget.value - widget.minValue) / _tempDiffValue;

    _radius = _superHeight / 2.0;
    _center = Offset(_superHeight / 2, _superHeight / 2);
    _position = Offset(_superHeight / 2, _superHeight / 2);
    _currentOffset =
        Offset(_superHeight / 2, _progressValue * _superHeight / 2);

    _currentColor = _gradientColor();

    super.initState();
  }

  @override
  void didUpdateWidget(covariant LightTempWidget oldWidget) {
    _progressValue = _superHeight * widget.value;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: const EdgeInsets.only(left: 18, right: 18, top: 18).r,
        child: Column(
          // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [_buildTitleWidget(), 4.sizedBoxWidth, _buildColorTemp()],
        ));
  }

  // 创建顶部标题
  Widget _buildTitleWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          width: 22.r,
          height: 22.r,
          child: SvgPicture.asset(
            SVGImage.icColortemperatureSvg,
            color: const Color.fromRGBO(168, 168, 168, 1),
          ),
        ),
        4.sizedBoxWidth,
        Text(
          '${_tempValue.toInt()}',
          style: 16.ts.copyWith(color: const Color.fromRGBO(222, 222, 222, 1)),
        ),
        2.sizedBoxWidth,
        Text(
          'K',
          style: 12.ts.copyWith(color: const Color.fromRGBO(168, 168, 168, 1)),
        ),
      ],
    );
  }

  // 色温圆盘
  Widget _buildColorTemp() {
    return ClipPath(
        clipper: LightTempClipper(),
        child: GestureDetector(
            onPanUpdate: _onPanUpdate,
            onPanDown: _onPanUpdate,
            child: Stack(
              children: [
                Container(
                  padding: const EdgeInsets.all(20).r,
                  alignment: Alignment.center,
                  width: 320.r,
                  height: 320.r,
                  child: Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(140.r),
                          gradient: const LinearGradient(
                              colors: [
                                Color.fromRGBO(255, 229, 124, 1),
                                Color.fromRGBO(255, 255, 255, 1),
                                Color.fromRGBO(209, 246, 255, 1)
                              ],
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter))),
                ),
                Positioned(
                  top: _currentOffset.dy,
                  left: _currentOffset.dx,
                  child: Container(
                    width: 38.r,
                    height: 38.r,
                    padding: const EdgeInsets.fromLTRB(28, 8, 28, 8).r,
                    decoration: BoxDecoration(
                      color: _currentColor,
                      borderRadius: BorderRadius.circular(19).r,
                      border: Border.all(width: 3, color: Colors.white),
                      boxShadow: const [
                        BoxShadow(
                          blurRadius: 10, //阴影范围
                          color: Color.fromRGBO(0, 0, 0, 0.50), //阴影颜色
                        ),
                      ],
                    ),
                  ),
                )
              ],
            )));
  }

  // 拖动手势变化
  void _onPanUpdate(details) {
    _position = Offset(details.localPosition.dx, details.localPosition.dy);

    double y = (sqrt(pow((_position.dx - _center.dx), 2) +
        pow((_position.dy - _center.dy), 2)));
    if (y <= _center.dx) {
      _currentOffset =
          Offset(details.localPosition.dx, details.localPosition.dy);
    } else {
      double dx = _position.dx - _center.dx;
      double dy = _position.dy - _center.dy;
      double distance = sqrt(dx * dx + dy * dy);
      double ratio = _radius / distance;
      _currentOffset = Offset(dx * ratio + _center.dx, dy * ratio + _center.dy);
    }

    String ratio = (_currentOffset.dy / _superHeight).toStringAsFixed(2);
    _progressValue = double.parse(ratio);
    _tempValue = widget.minValue + _tempDiffValue * _progressValue;
    // 返回当前色温
    widget.valueChanged(_tempValue);
    // 计算所在位置的具体色值
    _currentColor = _gradientColor();
    setState(() {});
  }

  ///获取象限
  static int getQuadrant(double x, double y, double size) {
    if (x >= size / 2) {
      return y >= size / 2 ? 3 : 4;
    }
    return y >= size / 2 ? 2 : 1;
  }

  // 计算从中心点渐变到边缘位置区间里具体位置的颜色
  late int _startR, _startG, _startB, _endR, _endG, _endB;
  late double _sR, _sG, _sB, _step;
  late Color _startColor, _endColor;
  Color _gradientColor() {
    if (_progressValue < 0.5) {
      _startColor = const Color.fromRGBO(255, 229, 124, 1);
      _endColor = const Color.fromRGBO(255, 255, 255, 1);
      _step = (280.r * _progressValue);
    } else if (_progressValue == 0.5) {
      return const Color.fromRGBO(255, 255, 255, 1);
    } else {
      _startColor = const Color.fromRGBO(255, 255, 255, 1);
      _endColor = const Color.fromRGBO(209, 246, 255, 1);
      _step = 280.r * (_progressValue - 0.5);
    }

    _startR = _startColor.red;
    _startG = _startColor.green;
    _startB = _startColor.blue;
    _endR = _endColor.red;
    _endG = _endColor.green;
    _endB = _endColor.blue;
    _sR = (_endR - _startR) / 140.r; //总差值
    _sG = (_endG - _startG) / 140.r;
    _sB = (_endB - _startB) / 140.r;

    int r = (_startR + _sR * _step).toInt();
    int g = (_startG + _sG * _step).toInt();
    int b = (_startB + _sB * _step).toInt();
    return Color.fromRGBO(r, g, b, 1);
  }
}

// 自定义绘制路径 切割出一个带弧形的contaner用于限制手势范围
class LightTempClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(size.width / 2.0, 0);
    path.arcToPoint(Offset(size.width / 2.0, size.width),
        clockwise: false, radius: Radius.circular(size.width / 2.0));
    path.moveTo(size.width / 2.0, size.width);
    path.arcToPoint(Offset(size.width / 2.0, 0),
        clockwise: false, radius: Radius.circular(size.width / 2.0));
    return path;
  }

  @override
  bool shouldReclip(LightTempClipper oldClipper) => true;
}
